from Bases import BaseObject
from ..gtkBaseUI import BaseContainer
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class GlobalAttributesView(BaseContainer):
    topwidget_name = 'Global Attributes Editor'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(GlobalAttributesView, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        self.DeviceSystem = self.MainController.DeviceSystem
        
        self.attribute_settings = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Attributes')
        col_names = ['id', 'name']
        obj_names=['GlobalAttribute']
        self.attributes_list = DeviceTree(col_names=col_names, obj_names=obj_names, child_name_attr='none', show_dicts=False, 
                                          base_dict=self.DeviceSystem.GlobalAttributes, used_columns=[1])
        self.attributes_list.widget.connect('selection_changed', self.on_attribute_list_selection_changed)
        
        frame.pack_start(self.attributes_list.widget.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewAttrib':'New Attribute', 'btnDelAttrib':'Delete'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_attribute_list_btns_clicked, k)
            hbox.pack_start(btn)
        frame.pack_start(hbox)
        
        self.topcontainer.pack_start(frame)
        
        self.DeviceSystem.connect('new_attribute', self.on_ds_new_attribute)
        
        self.topwidget.show_all()
        
    def set_current_attribute(self, obj):
        if self.attribute_settings is not None:
            self.attribute_settings.unlink()
            self.topcontainer.remove(self.attribute_settings.topwidget)
        self.attribute_settings = editors.AttributeEditor(MainController=self.MainController, attribute=obj)
        self.topcontainer.pack_start(self.attribute_settings.topwidget)
    
    def on_attribute_list_selection_changed(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('state')
        if state and hasattr(obj, 'id'):
            self.set_current_attribute(obj)
        
    def on_attribute_list_btns_clicked(self, btn, key):
        if key == 'btnNewAttrib':
            attrib = self.DeviceSystem.add_global_attribute(name='New Attribute')
            self.attributes_list.tree.set_selection(attrib.id)
        elif key == 'btnDelAttrib':
            obj = self.attributes_list.widget.selected_obj
            if obj is not None:
                self.DeviceSystem.del_global_attribute(attribute=obj)
                self.attributes_list.tree.refresh_all()
        
    def on_ds_new_attribute(self, **kwargs):
        self.attributes_list.tree.refresh_all()
        
